﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Globalization;
using log4net;

namespace ThreeByte.ActiveDeck.Data
{
    public class PresentationHeader
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(PresentationHeader));
        private static readonly XNamespace ns = Service.ServiceConfiguration.NAMESPACE;
        private static readonly CultureInfo usProvider = CultureInfo.CreateSpecificCulture("en-us");

        public string ID {
            get;
            private set;
        }

        public string Name {
            get;
            private set;
        }

        public int Version {
            get;
            private set;
        }

        public int PresentationCount {
            get;
            private set;
        }

        public DateTime LastModified {
            get;
            private set;
        }

        public PresentationHeader(XElement node) {
            ID = node.Attribute("ID").Value;
            Name = node.Attribute("Name").Value;
            Version = int.Parse(node.Attribute("Version").Value);
            
            try{
                LastModified = DateTime.ParseExact(node.Attribute("LastModified").Value, "G", usProvider);
            } catch(Exception ex){
                log.Error("Cannot parse LastModified time", ex);
                LastModified = DateTime.MinValue;
            }
            PresentationCount = int.Parse(node.Attribute("PresentationCount").Value);
        }

        public PresentationHeader(Presentation pres) {
            ID = pres.ID;
            Name = pres.Name;
            Version = pres.Version;
            LastModified = pres.LastModified ?? DateTime.MinValue;
            PresentationCount = pres.PresentationCount;
        }

        public XElement ToXml() {
            
            XElement presNode = new XElement(ns + "Presentation");
            presNode.Add(new XAttribute("ID", ID));
            presNode.Add(new XAttribute("Name", Name));
            //presNode.Add(new XAttribute("Created", Created));
            presNode.Add(new XAttribute("LastModified", LastModified.ToString(usProvider)));
            //presNode.Add(new XAttribute("LastPresented", pres.LastPresented.ToString()));
            presNode.Add(new XAttribute("Version", Version));
            presNode.Add(new XAttribute("PresentationCount", PresentationCount));
            return presNode;

        }
    }
}
